package com.bt.springboot.demo.algorithm.leetcode;

/**
 * Z字形变换
 * <p>
 * 将一个给定字符串 s 根据给定的行数 numRows ，以从上往下、从左到右进行 Z 字形排列。
 * <p>
 * 比如输入字符串为 "PAYPALISHIRING" 行数为 3 时，排列如下：
 * <p>
 * P   A   H   N
 * A P L S I I G
 * Y   I   R
 *
 * @author zkx
 * @Date 2022/9/27 14:00
 */
public class Topic06 {

	public static void main(String[] args) {
		String s = "asdasdaaads";
		Topic06 topic06 = new Topic06();
		System.out.println(topic06.convert(s, 3));
	}

	public String convert(String s, int numRows) {
		if (s == null || s.length() == 0 || numRows <= 1) {
			return s;
		}

		StringBuilder[] sb = new StringBuilder[numRows];
		for (int i = 0; i < sb.length; i++) {
			sb[i] = new StringBuilder();
		}

		int len = s.length();
		char[] chars = s.toCharArray();
		for (int i = 0; i < len; ) {
			for (int row = 0; row < numRows && i < len; row++) {
				sb[row].append(chars[i]);
				i++;
			}
			for (int row = numRows - 2; row >= 1 && i < len; row--) {
				sb[row].append(chars[i]);
				i++;
			}
		}

		StringBuilder result = new StringBuilder();
		for (StringBuilder strb : sb) {
			result.append(strb);
		}

		return result.toString();
	}
}
